<template>
  <div class="container">
    <van-nav-bar
      fixed
      left-arrow
      @click-left="$router.back()"
      title="小智同学"
    ></van-nav-bar>
    <!-- 聊天列表渲染 -->
    <div
      class="chat-list"
      ref="list"
    >
      <!-- 聊天对象A-小智同学 -->
      <!-- 动态渲染v-for -->
      <div
        class="chat-item"
        :class="{left: chat.name === 'xz',right:chat.name === 'self'}"
        v-for="(chat,i) in list"
        :key="i"
      >
        <van-image
          v-if="chat.name === 'xz'"
          fit="cover"
          round
          :src="xzTx"
        />
        <div class="chat-pao">{{chat.msg}}</div>
        <van-image
          v-if="chat.name === 'self'"
          fit="cover"
          round
          :src="photo"
        />
      </div>
      <!-- 聊天对象B-当前登录人 -->
      <!-- <div class="chat-item right">
        <div class="chat-pao">ewqewq</div>
        <van-image
          fit="cover"
          round
          src="https://img.yzcdn.cn/vant/cat.jpeg"
        />
      </div> -->
    </div>
    <!-- 聊天内容输入区域 -->
    <div class="reply-container van-hairline--top">
      <van-field
        v-model="value"
        placeholder="说点什么..."
      >
        <!-- 插槽控制聊天内容的提交 -->
        <span
          @click="send()"
          slot="button"
          style="font-size:12px;color:#999"
        >提交</span>
      </van-field>
    </div>
  </div>
</template>

<script>
// 引入本地图片
/**
 * 1. 通过import 导入 => base64
 * 2. 通过require导入 => 相对路径
 */
import { mapGetters } from 'vuex'
import xzTx from '@/assets/xz.png'
// const selfTx = require('@/assets/my.jpg')
import io from 'socket.io-client'
export default {
  name: 'user-chat',
  data () {
    return {
      // 小智的头像
      xzTx,
      // selfTx,
      // 聊天的数据
      // name 聊天对象 msg 聊天内容
      // 设计数据结构：[{name:'xz', msg:'你好！'},{name:'self', msg:'你好！小智'}]
      list: [],
      // 聊天内容
      value: ''
    }
  },
  computed: {
    ...mapGetters(['photo'])
  },
  created () {
    // this.createWs()
    this.createIo()
  },
  methods: {
    // 内容超过一屏滚动到最底部
    goBottom () {
      this.$nextTick(() => {
        console.log(this.$refs.list.scrollHeight)
        this.$refs.list.scrollTop = this.$refs.list.scrollHeight
      })
    },
    send () {
      // 把当前登录人说的话=》显示到聊天列表中
      this.list.push({ name: 'self', msg: this.value })
      // 向服务器发消息
      // this.ws.send(this.value)
      this.io.emit('message', { name: '小红', msg: this.value })
      // 清空上次输入的内容
      this.value = ''
    },
    // 使用插件socket.io开发
    createIo () {
      this.io = io('http://192.168.145.44:3000/', {
        transports: ['websocket'],
        query: {
          token: Math.random() * 1000
        }
      })
      this.io.on('connect', () => {
        console.log('连接成功！')
        this.list.push({ name: 'xz', msg: '你好，小红！' })
      })
      // 接收服务器发送的数据=>小智
      this.io.on('message', (data) => {
        // 显示服务器消息到聊天列表
        this.list.push({ name: 'xz', msg: data.msg })
        // 执行滚动底部
        this.goBottom()
      })
    },
    // 原生webscoket用法（了解）
    createWs () {
      /**
       * WebSocket用法=>类似打电话场景
       * 1. 建立连接（拨号）
       * 2. 通话（双向的）
       * 3. 通过结束，断开连接（挂电话）
       */
      // 建立连接=》创建ws实例
      this.ws = new WebSocket('ws://echo.websocket.org')
      this.ws.onopen = () => {
        console.log('连接建立成功！')
        // 客户端向服务器发送消息
        this.ws.send(Math.random() * 100)
      }
      // 接收服务器的消息=>小智
      this.ws.onmessage = (e) => {
        console.log('服务器发送的数据：', e.data)
        // 显示服务器返回的数据
        this.list.push({ name: 'xz', msg: e.data })
      }
      this.ws.onclose = () => {
        console.log('ws连接关闭了')
      }
    }
  },
  beforeDestroy () {
    // 关闭ws连接
    // this.ws.close()
    this.io.close()
  }
}
</script>

<style scoped lang='less'>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 46px 0 50px 0;
  .chat-list {
    height: 100%;
    overflow-y: scroll;
    .chat-item {
      padding: 10px;
      .van-image {
        vertical-align: top;
        width: 40px;
        height: 40px;
      }
      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 40px;
        line-height: 38px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 14px;
        color: #333;
        &::before {
          content: "";
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}
.chat-item.right {
  text-align: right;
  .chat-pao {
    margin-left: 0;
    margin-right: 15px;
    &::before {
      right: -6px;
      transform: rotate(45deg);
    }
  }
}
.chat-item.left {
  text-align: left;
  .chat-pao {
    margin-left: 15px;
    margin-right: 0;
    &::before {
      left: -5px;
      transform: rotate(-135deg);
    }
  }
}
.reply-container {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 44px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}
</style>
